<template>
  <el-form
    ref="form"
    class="form"
    v-if="model"
    :model="model"
    :validate-on-rule-change="false"
    :rules="rules"
    v-bind="$attrs"
    label-width="auto"
  >
    <template v-for="(item, index) in options" :key="index">
      <el-form-item
        v-if="!item.children || !item.children.length"
        :label="item.label"
        :prop="item.prop"
      >
        <component
          v-if="item.type !== 'upload' && item.type !== 'editor'"
          :is="`el-${item.type}`"
          :placeholder="item?.placeholder"
          v-model="model[item.prop]"
          v-bind="item.attrs"
        ></component>
        <el-upload
          v-if="item.type == 'upload'"
          v-bind="item.uploadAttrs"
          :on-preview="onPreview"
          :on-remove="onRemove"
          :on-success="onSuccess"
          :on-error="onError"
          v-model:file-list="model[item.prop]"
          :on-progress="onProgress"
          :on-change="(File, fileList) => onChange(File, fileList, index)"
          :before-upload="beforeUpload"
          :before-remove="beforeRemove"
          :http-request="httpRequest"
          :on-exceed="onExceed"
        >
          <!-- 默认插槽 -->
          <template #default>
            <slot name="uploadArea"></slot>
          </template>
          <!-- tips插槽 -->
          <template #tip>
            <slot name="uploadTip"></slot>
          </template>
          <!-- 触发文件选择框的内容 -->
          <!-- <slot name="trigger"></slot> -->
          <!-- 缩略图插件 传递file数据 -->
          <!-- <slot name="file" :file="{ file: UploadFile, index: number }"></slot> -->
        </el-upload>
        <div style="border: 1px solid #ccc" v-if="item.type == 'editor'">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
          <Editor
            style="height: 200px; overflow-y: auto"
            v-model="model[item.prop]"
            :defaultConfig="item?.editorConfig"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
      <el-form-item
        v-if="item.children && item.children.length"
        :label="item.label"
        :prop="item.prop"
      >
        <component
          :is="`el-${item.type}`"
          :placeholder="item?.placeholder"
          v-model="model[item.prop]"
          v-bind="item.attrs"
        >
          <!-- 子组件 使用slot渲染 -->
          <component
            v-for="(child, i) in item.children"
            :key="i"
            :is="`el-${child.type}`"
            :label="child.label"
            :value="child.value"
            v-bind="child.attrs"
          >
          </component>
        </component>
      </el-form-item>
    </template>
    <!-- 表单操作栏 -->
    <el-form-item>
      <slot name="action" :form="form" :model="model"></slot>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { cloneDeep } from "lodash-es";
import type { FormInstance } from "element-plus";
import {
  shallowRef,
  PropType,
  onMounted,
  ref,
  watch,
  onBeforeUnmount,
} from "vue";
import { FormOptionsVO } from "./types/types.ts";

let emits = defineEmits([
  "on-preview",
  "on-remove",
  "on-success",
  "on-error",
  "on-progress",
  "on-change",
  "before-upload",
  "before-remove",
  "on-exceed",
]);

const props = defineProps({
  options: {
    type: Array as PropType<FormOptionsVO[]>,
    required: true,
  },
  // 用户自定义上传方法
  httpRequest: {
    type: Function,
  },
});
let form = ref<FormInstance>();
let model = ref<any>(null);
let rules = ref<any>(null);
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
function initForm() {
  if (props.options && props.options.length) {
    let m: any = {};
    let r: any = {};
    props.options!.forEach((item: FormOptionsVO) => {
      m[item.prop] = item.value;
      r[item.prop] = item.rules;
    });
    model.value = cloneDeep(m);
    rules.value = cloneDeep(r);
  }
}

//监听options改变后，重新初始化表单
watch(
  () => props.options,
  () => {
    initForm();
  },
  { deep: true }
);

onMounted(() => {
  initForm();
});

// 上传组件的所有方法
let onPreview = (file: File) => {
  emits("on-preview", file);
};
let onRemove = (file: File, fileList: FileList) => {
  emits("on-remove", { file, fileList });
};
let onSuccess = (response: any, file: File, fileList: FileList) => {
  // 上传图片成功 给表单上传项赋值

  emits("on-success", { response, file, fileList });
};
let onError = (err: any, file: File, fileList: FileList) => {
  emits("on-error", { err, file, fileList });
};
let onProgress = (event: any, file: File, fileList: FileList) => {
  emits("on-progress", { event, file, fileList });
};
let onChange = (file: File, fileList: FileList, itemIndex: number) => {
  // 上传组件有更新 就更新上传组件的值
  let uploadItem = props.options![itemIndex];
  model.value[uploadItem.prop] = fileList;
  form.value?.validateField(uploadItem.prop);
  emits("on-change", { file, fileList });
};
let beforeUpload = (file: File) => {
  emits("before-upload", file);
};
let beforeRemove = (file: File, fileList: FileList) => {
  emits("before-remove", { file, fileList });
};
let onExceed = (files: File, fileList: FileList) => {
  emits("on-exceed", { files, fileList });
};

const validate = (callBack) => {
  return form.value?.validate(callBack);
};
const resetFields = () => {
  return form.value?.resetFields();
};

const getModelData = () => {
  return cloneDeep(model.value);
};

//分发方法
defineExpose({
  validate,
  resetFields,
  getModelData,
});
</script>
<style lang="scss" scoped></style>
